package com.yuezhi.mylauncher.broadcastreceivers;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;

import com.yuezhi.mylauncher.activities.MainActivity;

/**
 * 实现开机启动
 *
 * @author Bai Yanchao
 * @since 2023/06/02 14:12
 */
public class AutoStartReceiver extends BroadcastReceiver {

    private Context context;
    private final AutoStartHandler handler = new AutoStartHandler(Looper.getMainLooper());

    @SuppressLint("UnsafeProtectedBroadcastReceiver")
    @Override
    public void onReceive(Context context, Intent intent) {
        this.context = context;
        handler.sendEmptyMessage(0);
    }

    private class AutoStartHandler extends Handler {
        public AutoStartHandler(@NonNull Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                Intent i = new Intent(context, MainActivity.class);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(i);
                handler.removeCallbacksAndMessages(null);
            }
        }
    }
}